package com.codedog.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import com.codedog.constant.UrlConstant;
import com.codedog.entity.UserInfo;
import com.codedog.enums.ResponseCodeEnum;
import com.codedog.exception.CustomException;

import java.io.File;

public class CodeDogCookieUtil {

    public static String getCookie() {
        File defaultConfigUrl = new File(UrlConstant.DEFAULT_CONFIG_URL);
        File cookieFile = FileUtil.file(UrlConstant.DEFAULT_CONFIG_URL + UrlConstant.DEFAULT_COOKIE_NAME);
        String cookieStr = null;
        if (!defaultConfigUrl.exists()) {
            FileUtil.touch(cookieFile);
        }
        if (FileUtil.isEmpty(cookieFile)) {
            FileUtil.touch(cookieFile);
            System.out.println("创建默认配置文件夹");
            while (!checkCookie(cookieStr)) {
                throw new CustomException(ResponseCodeEnum.COOKIE_INVALID);
            }
            FileUtil.writeString(cookieStr, cookieFile, CharsetUtil.UTF_8);
        } else {
            FileReader fileReader = new FileReader(cookieFile);
            cookieStr = fileReader.readString();
        }
        return cookieStr;
    }

    public static Integer updateCookie(String cookie) {
        File defaultConfigUrl = new File(UrlConstant.DEFAULT_CONFIG_URL);
        File cookieFile = FileUtil.file(UrlConstant.DEFAULT_CONFIG_URL + UrlConstant.DEFAULT_COOKIE_NAME);
        if (defaultConfigUrl.exists()) {
            delCookie();
        }
        FileUtil.touch(cookieFile);
        while (!checkCookie(cookie)) {
            return ResponseCodeEnum.COOKIE_INVALID.getCode();
        }
        FileUtil.writeString(cookie, cookieFile, CharsetUtil.UTF_8);
        return ResponseCodeEnum.OK.getCode();
    }

    public static Boolean checkCookie(String cookie) {
        Boolean cookieGood = false;
        UserInfo userInfo = CodeDogHTTPUtil.getUserInfo(cookie);
        if (StrUtil.isNotEmpty(userInfo.getFullname())) {
            cookieGood = true;
        }
        return cookieGood;
    }

    public static void delCookie() {
        FileUtil.del(UrlConstant.DEFAULT_CONFIG_URL + UrlConstant.DEFAULT_COOKIE_NAME);
    }
}